//
//  NYDetailContentViewController.m
//  NiuWaJiaoYu
//
//  Created by MinLison on 2018/1/10.
//  Copyright © 2018年 niuwaketang. All rights reserved.
//
//#import <DMPlayer/DMPlayer.h>
#import "NYDetailContentViewController.h"
#import "NYPageViewController.h"
#import "NYDetailExerciseViewController.h"
#import "NYDetailChaptersViewController.h"
#import "NYDetailQuestionViewController.h"
#import "NYDetailSelfTestViewController.h"
//models
#import "NYCourseModel.h"
#import "NYDetailContentBottomTableCellModel.h"
/// views
#import "BaseTableHeaderFooterView.h"
#import "NYDetailContentTitleHeaderView.h"
/// cells
#import "NYDetailContentDesCell.h"
#import "NYDetailContentActionCell.h"
#import "NYSubjectTitleCell.h"
#import "NYExamineTestTextViewCell.h"
#import "NYSubjectAnswerCell.h"
#import "NYExamineTestActionCell.h"
#import "NYAddToGoodSubjectRequest.h"

// request
#import "NYDetailAddClassRequest.h"
#import "NYDetailCompleteVideoRequest.h"
#import "NYCourseRequest.h"
#import "NYVideoLevalMsgRequest.h"
#import "NYMessageListRequest.h"

#import "ZFPlayer.h"
#import "ZFAVPlayerManager.h"
#import "ZFPlayerController.h"
#import "ZFPlayerControlView.h"
#import "KSMediaPlayerManager.h"
#import "ZFPlayerMediaPlayback.h"

#define NYMaskPlayerColor colorWithRed:33/255.0 green:37/255.0 blue:35/255.0 alpha:1

@interface NYDetailContentViewController ()<WGPageViewControllerDelegate>
@property(nonatomic, strong) NYPageViewController *pageViewController;
@property(nonatomic, strong) NYDetailContentBottomTableCellModel *contentCellModel;

@property (nonatomic, strong) NYCourseModel *detailModel;
@property (nonatomic, strong) NSMutableDictionary *paraDictionary;
@property(nonatomic, strong) NYVideoModel *currentPlayModel;
@property(nonatomic, assign) NSInteger currentPlayIndex;
@property(nonatomic, strong) NYCourseRequest *request;
@property (nonatomic, assign) NYExamineRequestStatus status;

@property (nonatomic, strong) ZFPlayerController *player;
@property (nonatomic, strong) ZFPlayerControlView *controlView;
@property (nonatomic, strong) UIView * FatherZFPlayerView;

@end

@implementation NYDetailContentViewController

#pragma mark - Life Cycle Methods
- (instancetype)initWithParaDictionary:(NSDictionary *)paraDcitionary
                       withDeatilModel:(NYCourseModel *)detailModel {
    self = [super init];
    if (self) {
        [self.paraDictionary addEntriesFromDictionary:paraDcitionary];
        self.detailModel = detailModel;
    }
    return self;
}
- (instancetype)initWithParaDictionary:(NSDictionary *)paraDcitionary withDeatilModel:(NYCourseModel *)detailModel preparePlayModel:(NYVideoModel *)model preparePlayModelIndex:(NSInteger)preparePlayModelIndex examineStatus:(NYExamineRequestStatus)status
{
    self = [super init];
    if (self) {
        self.status = status;
        [self.paraDictionary addEntriesFromDictionary:paraDcitionary];
        self.detailModel = detailModel;
        self.currentPlayModel = model;
        self.currentPlayIndex = preparePlayModelIndex;
        
        [self saveTheLearnRecordModel:detailModel];
    }
    return self;
}

- (void)initZF {
    ZFAVPlayerManager *playerManager = [[ZFAVPlayerManager alloc] init];
    self.player = [ZFPlayerController playerWithPlayerManager:playerManager containerView:self.FatherZFPlayerView];
    self.player.controlView = self.controlView;
    self.player.lockedScreen = NO;
    /// 设置退到后台继续播放
    self.player.pauseWhenAppResignActive = NO;
    @weakify(self)
    self.player.orientationWillChange = ^(ZFPlayerController * _Nonnull player, BOOL isFullScreen) {
        @strongify(self)
        [self setNeedsStatusBarAppearanceUpdate];
    };
    self.player.pauseByEvent = YES;
    /// 播放准备就绪手动播放
    self.player.playerPrepareToPlay = ^(id<ZFPlayerMediaPlayback>  _Nonnull asset, NSURL * _Nonnull assetURL) {

    };
    /// 播放状态切换暂停播放**
    self.player.playerLoadStateChanged = ^(id<ZFPlayerMediaPlayback>  _Nonnull asset, ZFPlayerLoadState loadState) {
        @strongify(self)
        self.player.pauseByEvent = YES;
    };
    /// 播放完自动播放下一个
    self.player.playerDidToEnd = ^(id  _Nonnull asset) {
        @strongify(self)
        [self.player seekToTime:0 completionHandler:^(BOOL finished) {
            [playerManager pause];
        }];
    };
}

- (BOOL)shouldAutorotate {
    return self.player.shouldAutorotate;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    if (self.player.isFullScreen && self.player.orientationObserver.fullScreenMode == ZFFullScreenModeLandscape) {
        return UIInterfaceOrientationMaskLandscape;
    }
    return UIInterfaceOrientationMaskPortrait;
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    if (self.player.isFullScreen) {
        return UIStatusBarStyleLightContent;
    }
    return UIStatusBarStyleDefault;
}

- (BOOL)prefersStatusBarHidden {
    return self.player.isStatusBarHidden;
}

- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
    return UIStatusBarAnimationSlide;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self loadData];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.player.viewControllerDisappear = NO;
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if ( !self.player.isFullScreen ) {
        self.player.viewControllerDisappear = YES;
    }
}
- (void)didInitializedWithStyle:(UITableViewStyle)style
{
    self.contentCellModel = [[NYDetailContentBottomTableCellModel alloc] init];
    [self configPageViewController];
    [super didInitializedWithStyle:style];
}
- (void)initSubviews
{
    [super initSubviews];
    self.FatherZFPlayerView = [[UIView alloc]init];
    [self initZF];
    self.controllerView.playerView = self.FatherZFPlayerView;
    self.controllerView.userInteractionEnabled = YES;

    @weakify(self);
    self.controllerView.messageButtonHandle = ^{
        
        @strongify(self);
        [self showCommentViewWithCleanText:NO];
    };
    self.tableView.bounces = NO;
}
- (void)configNavigationBar:(BaseNavigationBar *)navigationBar
{
    [super configNavigationBar:navigationBar];
    
    self.title = (_status == NYExamineRequestStatusCup) ? @"杯赛" : @"选课";
}

- (void)loadData
{
    [self setLoading:YES animation:YES];
    self.request = [NYCourseRequest requestWithType:self.status param:self.paraDictionary];
    [self.request paramInsert:@(self.currentPlayModel.id) forKey:kRequestVideoID];
    [self.request startWithSuccess:^(__kindof BaseRequest * _Nonnull request, __kindof NYCourseModel * _Nonnull data) {
        
        self.detailModel = data;
        self.detailModel.currentPlayIndex = self.currentPlayIndex;
        self.detailModel.currentPlayModel = [self.detailModel.video jk_objectWithIndex:self.currentPlayIndex];
        
        [self configNimbusData];
        [self setSuccess];
        [self autoPlayWithCourseModel:data videoModel:self.currentPlayModel videoModelIndex:self.currentPlayIndex];
    } failed:^(__kindof BaseRequest * _Nonnull request, NSError * _Nonnull error) {
        [self setError:error];
    }];
    
}
- (UITableViewCell *)tableViewModel:(NITableViewModel *)tableViewModel cellForTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath withObject:(id)object
{
    UITableViewCell *cell = [super tableViewModel:tableViewModel cellForTableView:tableView atIndexPath:indexPath withObject:object];
    if ([cell isKindOfClass:[NYDetailContentActionCell class]]) {
        [self configActionCell:(NYDetailContentActionCell *)cell];
    }else  if ([cell isKindOfClass:[NYExamineTestActionCell class]]) {
        [self configTestActionCell:(NYExamineTestActionCell *)cell];
    }
    return cell;
}
- (void)configNimbus
{
    [super configNimbus];
    self.tableView.allowsSelection = NO;
    self.tableView.allowsMultipleSelection = NO;
    [self.tableViewActions forwardingTo:self];
    [self.tableView registerClass:[BaseTableHeaderFooterView class] forHeaderFooterViewReuseIdentifier:[BaseTableHeaderFooterView className]];
    [self.tableView registerClass:[NYDetailContentTitleHeaderView class] forHeaderFooterViewReuseIdentifier:[NYDetailContentTitleHeaderView className]];
}
- (void)configNimbusData
{
    [self configNimbus];
    [self.tableView setContentOffset:CGPointZero animated:NO];
    [self.tableViewModel removeAll];
    [self.tableView reloadData];
    
    self.contentCellModel.offset = 0;
    /// 如果是0 ，则表示是描述
    /// section 0 描述
    [self.tableViewModel addSectionWithTitle:nil];
    /// 描述
    [self.tableViewModel addObject:[NICellObject objectWithCellClass:[NYDetailContentDesCell class] userInfo:self.detailModel]];
    
    /// 按钮
    /// seciton 1
    [self.tableViewModel addSectionWithTitle:nil];
    [self.tableViewModel addObject:[NICellObject objectWithCellClass:[NYDetailContentActionCell class] userInfo:self.detailModel]];
    /// 底部四个控制器
    /// section 2
    [self.tableViewModel addSectionWithTitle:nil];
    [self.tableViewModel addObject:self.contentCellModel];
    [self.tableView reloadData];
    [self reloadPageViewController];
    
    [self.tableView setContentOffset:CGPointZero animated:YES];
}

- (void)configTestActionCell:(NYExamineTestActionCell *)actionCell
{
    @weakify(self);
    @weakify(actionCell);
    [actionCell setActionBlock:^(NYExamineTestActionType actionType,  NYSubjectModel *questionModel) {
        @strongify(self);
        @strongify(actionCell);
        switch (actionType) {
            case NYExamineTestActionTypeAnalysis:
            {
                
                NYSubjectAnalysisType type;
                if (self.status == NYExamineRequestStatusCup) {
                    
                    type = NYSubjectAnalysisTypeCutGame;
                } else if (self.status == NYExamineRequestStatusChoose) {
                    
                    type = NYSubjectAnalysisTypeExaminationAnalysis;
                } else {
                    type = NYSubjectAnalysisTypeExamine;
                }
                [self routeUrl:kNYSubjectAnalysisURI param:@{
                                                             kRequestKeyType : @(type),
                                                             kRequestKeyTypeID : NOT_NULL_STRING_DEFAULT_EMPTY(questionModel.id)
                                                             }];
            }
                break;
            case NYExamineTestActionTypeAddToGood:
            {
                [[NYAddToGoodSubjectRequest requestWithParams:@{
                                                                kRequestKeyExercisesId : NOT_NULL_STRING_DEFAULT_EMPTY(questionModel.id),
                                                                kRequestKeyTypeID : @(questionModel.genre?: NYGenreTypeExamination),
                                                                }] startWithSuccess:^(__kindof BaseRequest * _Nonnull request, __kindof NSString * _Nonnull data) {
                    [NYTipClass showText:request.tipString inView:self.view];
                    questionModel.is_good = @"2";
                    [self.tableView reloadRowAtIndexPath:[self.tableView indexPathForCell:actionCell] withRowAnimation:(UITableViewRowAnimationNone)];
                } failed:^(__kindof BaseRequest * _Nonnull request, NSError * _Nonnull error) {
                    [NYTipClass showErrorWithText:error.localizedDescription inView:self.view];
                }];
            }
                break;
                
            default:
                break;
        }
        
    }];
}
- (void)configActionCell:(NYDetailContentActionCell *)cell
{
    @weakify(self);
    cell.actionBlock = ^(NYDetailContentActionType actionType, NYCourseModel *questionModel) {
        @strongify(self);
        switch (actionType) {
            case NYDetailContentActionTypeAddToMyClasses:
            {
                [NYTipClass showLoadingInView:self.view];
                [[NYDetailAddClassRequest requestWithParams:@{
                                                              kRequestKeyCourseID : @(questionModel.id),
                                                              kRequestKeyTypeID : @(1)
                                                              }] startWithSuccess:^(__kindof BaseRequest * _Nonnull request, __kindof id  _Nonnull data) {
                    [NYTipClass showText:request.tipString inView:self.view];
                    (questionModel.join_my_course == 1) ? (questionModel.join_my_course = 2) : (questionModel.join_my_course = 1);
                    [self.tableView reloadSection:1 withRowAnimation:(UITableViewRowAnimationNone)];
                } failed:^(__kindof BaseRequest * _Nonnull request, NSError * _Nonnull error) {
                    [NYTipClass showErrorWithText:error.localizedDescription inView:self.view];
                }];
            }
                break;
            case NYDetailContentActionTypeCompleteClasses:
            {
                [NYTipClass showLoadingInView:self.view];
                [[NYDetailCompleteVideoRequest requestWithParams:@{
                                                              kRequestKeyCourseID : @(questionModel.id),
                                                              kRequestKeyTypeID : @(1),
                                                              @"video_id" : @(1)
                                                              }] startWithSuccess:^(__kindof BaseRequest * _Nonnull request, __kindof id  _Nonnull data) {
                    [NYTipClass showText:request.tipString inView:self.view];
                    (questionModel.currentPlayModel.is_learn == 1) ? (questionModel.currentPlayModel.is_learn = 2) : (questionModel.currentPlayModel.is_learn = 1);
                    [self.tableView reloadSection:1 withRowAnimation:(UITableViewRowAnimationNone)];
                } failed:^(__kindof BaseRequest * _Nonnull request, NSError * _Nonnull error) {
                    [NYTipClass showErrorWithText:error.localizedDescription inView:self.view];
                }];
            }
                break;
                
            default:
                break;
        }
    };
}
/// Player
- (void)autoPlayWithCourseModel:(NYCourseModel *)courseModel videoModel:(NYVideoModel *)videoModel videoModelIndex:(NSInteger)videoModelIndex
{
    UIColor * MaskColor = [UIColor NYMaskPlayerColor];
    [self.controlView showTitle:videoModel.video_title coverImage:[[UIImage imageWithColor:MaskColor] imageWithRenderingMode:UIImageRenderingModeAutomatic] fullScreenMode:ZFFullScreenModeLandscape];
    //    [self.controlView showTitle:videoModel.video_title coverURLString:courseModel.ucloud_video_pic fullScreenMode:ZFFullScreenModeLandscape];
    self.player.assetURL = [NSURL URLWithString:courseModel.ucloud_video_url];
    //不自动播放，暂停
    self.player.pauseByEvent = YES;
    self.player.shouldAutoPlay = NO;
    
    self.currentPlayIndex = videoModelIndex;
    self.currentPlayModel = videoModel;
    self.detailModel.currentPlayModel = videoModel;
    self.detailModel.currentPlayIndex = videoModelIndex;
    [self.tableView reloadSection:1 withRowAnimation:(UITableViewRowAnimationNone)];
    
//    ZFPlayerModel *playerModel = [[ZFPlayerModel alloc] init];
//    playerModel.title = videoModel.video_title;
//    playerModel.videoURL = [NSURL URLWithString:courseModel.ucloud_video_url];
//    playerModel.placeholderImage = [UIImage selectionHolder];
//    playerModel.placeholderImageURLString = courseModel.ucloud_video_pic;
//    playerModel.identifier = [NSString stringWithFormat:@"%ld_%@",(long)videoModel.id,videoModel.video_title].md5String;
//    NSNumber *time = (NSNumber *)[ShareStaticCache objectForKey:playerModel.title.md5String];
//    playerModel.seekTime = time.floatValue;
//    playerModel.scrollView       = self.tableView;
//    playerModel.loadBarranges = ^(ZFPlayerModel *playerModel, DMBarrage completion) {
//
//    };
//    playerModel.sendBarrangeText = ^BOOL(ZFPlayerModel *playerModel, UIView *showTipView, NSString *editString, NSInteger playTime, DMCanSendBarrage canSend) {
//        return NO;
//    };
//
//    playerModel.editFilter = ^BOOL(ZFPlayerModel *playerModel, UIView *showTipView, NSString *editString) {
//        return YES;
//    };
//    playerModel.playEnd = ^(ZFPlayerModel *playerModel, NSInteger currentTime, BOOL isFinished) {
//        [ShareStaticCache setObject:@(currentTime) forKey:playerModel.title.md5String];
//    };
//    playerModel.fatherView = self.controllerView.playerContentView;
//    // 赋值分辨率字典
//    //        playerModel.resolutionDic    = dic;
//    // player的父视图tag
//    playerModel.fatherViewTag    = self.controllerView.playerContentView.tag;
//
//    // 设置播放控制层和model
//    [self.playerView playerModel:playerModel];
//    // 自动播放
//    [self.playerView pause];
}

/// PageViewController
- (void)reloadPageViewController
{
//    self.pageViewController.segmentTitles = @[@"练习题",@"章节",@"问答",@"自测卷"];
    
    self.pageViewController.segmentTitles = (_status == NYExamineRequestStatusCup) ? @[@"杯赛考试",@"章节",@"问答"] : @[@"练习题",@"章节",@"问答"];

    [self.pageViewController reloadData];
}
- (void)configPageViewController
{
    self.pageViewController = [[NYPageViewController alloc] init];
    [self.pageViewController willMoveToParentViewController:self];
    [self addChildViewController:self.pageViewController];
    self.contentCellModel.commentContentView = self.pageViewController.view;
    self.pageViewController.customTopSortView = YES;
    [self.pageViewController didMoveToParentViewController:self];
    self.pageViewController.pageDelegate = self;
    self.pageViewController.topSortBottomLineColor = UIColorSeparator;
    self.pageViewController.segmentControl.segmentWidthStyle = HMSegmentedControlSegmentWidthStyleFixed;
    self.pageViewController.segmentControl.selectedTitleTextAttributes = @{
                                                                           NSForegroundColorAttributeName : UIColorHex(0x5396F7),
                                                                           NSFontAttributeName : WGSystem13Font,
                                                                           };
    self.pageViewController.segmentControl.titleTextAttributes = @{
                                                                   NSForegroundColorAttributeName : UIColorHex(0x999999),
                                                                   NSFontAttributeName : WGSystem13Font,
                                                                   };
    self.pageViewController.segmentControl.selectionIndicatorEdgeInsets = UIEdgeInsetsMake(0, -3, 0, -3);
    self.pageViewController.segmentControl.selectionIndicatorColor = UIColorHex(0x5396F7);
    self.pageViewController.segmentControl.segmentEdgeInset = UIEdgeInsetsMake(0, __WGWidth(10), 0, __WGWidth(10));
    self.pageViewController.segmentLayoutEdgeInsets = UIEdgeInsetsMake(0, __WGWidth(60), 1, __WGWidth(60));
    self.pageViewController.topSortBottomLineColor = [UIColor clearColor];
    self.pageViewController.topSortView.qmui_borderPosition = QMUIBorderViewPositionBottom;
    
}
/// MARK: - Action
- (void)playVideo:(NYVideoModel *)videoModel atIndex:(NSInteger)index
{
    self.currentPlayIndex = index;
    self.currentPlayModel = videoModel;
    [self.tableView setContentOffset:CGPointZero animated:NO];
    // 播放
    @weakify(self);
    NYCourseRequest *request = [NYCourseRequest requestWithType:self.status param:self.paraDictionary];;
    [request paramInsert:@(videoModel.id) forKey:kRequestVideoID];
    [request startWithSuccess:^(__kindof BaseRequest * _Nonnull request, __kindof NYCourseModel * _Nonnull data) {
        @strongify(self);
        [self.detailModel modelSetWithJSON:[data modelToJSONString]];
        [self configNimbusData];
        [self autoPlayWithCourseModel:data videoModel:videoModel videoModelIndex:index];
        
    } failed:^(__kindof BaseRequest * _Nonnull request, NSError * _Nonnull error) {
        @strongify(self);
        [NYTipClass showErrorWithText:request.tipString inView:self.view];
    }];
}
/// MARK: - TableView Delegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    /// 第一个，文字 header， 2，底部四个控制器
    if (section == 0 || section == 2)
    {
        return __WGHeight(41);
    }
    /// 按钮
    if (section == 1)
    {
        return __WGHeight(10);
    }
    if (@available(iOS 11, *)) {
        return CGFLOAT_MIN;
    }
    return 0.0001;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    /// 倒数第二个，按钮
    if (section == 1)
    {
        return __WGHeight(10);
    }
    if (@available(iOS 11, *)) {
        return CGFLOAT_MIN;
    }
    return 0.0001;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    BaseTableHeaderFooterView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:[BaseTableHeaderFooterView className]];
    view.contentView.backgroundColor = UIColorForBackground;
    return view;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    /// 标题
    if (section == 0) {
        NYDetailContentTitleHeaderView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:[NYDetailContentTitleHeaderView className]];
        header.title = self.detailModel.title;
        return header;
    }
    BaseTableHeaderFooterView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:[BaseTableHeaderFooterView className]];

    /// 最后一个，底部四个控制器
    if (section == 2)
    {
        [self.pageViewController.topSortView removeFromSuperview];
        [header addSubview:self.pageViewController.topSortView];
        [self.pageViewController.topSortView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(header);
        }];
        return header;
    }
    return header;
}
/// MARK: - PageController Delegate
- (NSInteger)countOfContentItems
{
    return self.pageViewController.segmentTitles.count;
}

- (UIViewController *)contentControllerAtIndex:(NSInteger)index
{
    @weakify(self);
    switch (index)
    {
        case 0:
        {
            NYDetailExerciseViewController *vc =  [[NYDetailExerciseViewController alloc] init];
            vc.detailModel = self.detailModel;
            return vc;
        }
            break;
        case 1:
        {
            NYDetailChaptersViewController *vc =  [[NYDetailChaptersViewController alloc] init];
            vc.detailModel = self.detailModel;
            vc.startIndex = self.currentPlayIndex;
            vc.detailChaptersPlayBlock = ^(NYCourseModel *detailModel, NYVideoModel *videoModel, NSInteger index) {
                @strongify(self);
                [self playVideo:videoModel atIndex:index];
                
                [self saveTheLearnRecordModel:detailModel];
            };
            return vc;
        }
            break;
        case 2:
        {
            NYDetailQuestionViewController *vc =  [[NYDetailQuestionViewController alloc] init];
            vc.detailModel = self.detailModel;
            return vc;
        }
            break;
        case 3:
        {
//            NYDetailSelfTestViewController *vc = [[NYDetailSelfTestViewController alloc] initWithExamineRequestStatus:self.status witModel:self.detailModel];
//            return vc;
        }
            break;
            
        default:
            break;
    }
    return nil;
}

- (void)configController:(BaseTableViewController *)controller atIndex:(NSInteger)index
{
    @weakify(self);
    switch (index)
    {
        case 0:
        {
            NYDetailExerciseViewController *vc =  (NYDetailExerciseViewController *)controller;
            vc.detailModel = self.detailModel;
        }
            break;
        case 1:
        {
            NYDetailChaptersViewController *vc =  (NYDetailChaptersViewController *)controller;
            vc.detailModel = self.detailModel;
            vc.startIndex = self.currentPlayIndex;
            vc.detailChaptersPlayBlock = ^(NYCourseModel *detailModel, NYVideoModel *videoModel, NSInteger index) {
                @strongify(self);
                [self playVideo:videoModel atIndex:index];
            };
        }
            break;
        case 2:
        {
            NYDetailQuestionViewController *vc =  (NYDetailQuestionViewController *)controller;
            vc.detailModel = self.detailModel;
        }
            break;
        case 3:
        {
//            NYDetailSelfTestViewController *vc = (NYDetailSelfTestViewController *)controller;
//            vc.detailModel = self.detailModel;
        }
            break;
            
        default:
            break;
    }
}

- (void)controllerDidShow:(BaseTableViewController *)controller atIndex:(NSInteger)index
{
    @weakify(self);
    [self.KVOController observe:controller.tableView keyPath:@keypath(controller.tableView,contentOffset) options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) block:^(BaseTableViewController *  _Nullable observer, BaseTableView *  _Nonnull object, NSDictionary<NSString *,id> * _Nonnull change) {
        @strongify(self);
        
        CGPoint offset = [change[NSKeyValueChangeNewKey] CGPointValue];
        if ( CGPointEqualToPoint(offset, CGPointZero) )
        {
            return;
        }
        /// 上移
        CGRect section1Rect = [self.tableView rectForHeaderInSection:[self.tableViewModel numberOfSection] - 1];
        if (offset.y > 0 && self.tableView.contentOffset.y < section1Rect.origin.y - 1)
        {
            [self.tableView setContentOffset:CGPointMake(0, section1Rect.origin.y) animated:YES];
            [object setContentOffset:CGPointZero animated:NO];
            return;
        }
        else if (offset.y < 0 )
        {
            [self.tableView setContentOffset:CGPointZero animated:YES];
            [object setContentOffset:CGPointZero animated:NO];
            return;
        }
    }];
}
/**
 /// 点击发送按钮的回调
 
 @param commentView 评论框
 @param hideBlock 网络请求后，隐藏调用
 @param cleanTextBlock 网络请求后，清理输入框文字调用
 */
- (void)commentViewSendButtonDidClick:(id<BaseCommentToolBarProtocol>)commentView hideBlock:(void (^)(BOOL))hideBlock cleanTextBlock:(void (^)(BOOL))cleanTextBlock
{
    FOUNDATION_EXTERN  NSString *const kRequestKeyCupMsgID;
    FOUNDATION_EXTERN  NSString *const kRequestKeyChooseMsgID;
    
    NSString *messageType = (_status == NYExamineRequestStatusCup) ? kRequestKeyCupMsgID : kRequestKeyChooseMsgID;

    @weakify(self);

    [[NYVideoLevalMsgRequest requestWithType:_status param:@{
                                                             messageType :NOT_NULL_STRING_DEFAULT_EMPTY(@(self.currentPlayModel.id).stringValue),
                                                             kRequestKeyContent :                                                      NOT_NULL_STRING_DEFAULT_EMPTY(commentView.text),
                                                             
                                                             }] startWithSuccess:^(__kindof BaseRequest * _Nonnull request, __kindof id  _Nonnull data) {
        @strongify(self);
        [NYTipClass showText:@"留言成功！请耐心等待老师回答。"];
        [self hideCommentViewWithCleanText:true force:true];
        [self loadMessageListRequest];
    } failed:^(__kindof BaseRequest * _Nonnull request, NSError * _Nonnull error) {

    }];
}
- (void)loadMessageListRequest {

    NSDictionary *paraDict = @{};
    if (_status == NYExamineRequestStatusChoose) {
        
        paraDict = @{
                     kRequestKeyChannel:@(NYUserManager.channelID),
                     kRequestKeyLoginCode : NOT_NULL_STRING_DEFAULT_EMPTY(NYUserManager.logincode), kRequestKeyUser_ID:NOT_NULL_STRING_DEFAULT_EMPTY(NYUserManager.user_id), kRequestKeyCourseID :NOT_NULL_STRING_DEFAULT_EMPTY(@(self.detailModel.id).stringValue),
                     kRequestVideoID :NOT_NULL_STRING_DEFAULT_EMPTY(@(self.currentPlayModel.id).stringValue)
                     };
    } else if (_status == NYExamineRequestStatusCup) { //杯赛
        paraDict = @{
                     kRequestKeyChannel:@(NYUserManager.channelID),
                     kRequestKeyLoginCode : NOT_NULL_STRING_DEFAULT_EMPTY(NYUserManager.logincode), kRequestKeyUser_ID:NOT_NULL_STRING_DEFAULT_EMPTY(NYUserManager.user_id), kRequestKeyCupID :NOT_NULL_STRING_DEFAULT_EMPTY(@(self.detailModel.id).stringValue),
                     kRequestVideoID :NOT_NULL_STRING_DEFAULT_EMPTY(@(self.currentPlayModel.id).stringValue)
                     };

    }
    NYMessageListRequest *request = [NYMessageListRequest requestWithType:_status param:paraDict];
    @weakify(self);
    [request startWithSuccess:^(__kindof BaseRequest * _Nonnull request, __kindof NSArray<NYAirlineItemModel *> * _Nonnull data) {
        
        @strongify(self);
        self.detailModel.message = data;
        [self.pageViewController reloadData];
    } failed:^(__kindof BaseRequest * _Nonnull request, NSError * _Nonnull error) {
    }];
    
}
/**
 返回对应评论框类型
 
 @return 暂时用这个吧，自动增加行高的不能用了
 */
- (BaseCommentToolBarType)commentToolBarType
{
    return BaseCommentToolBarTypeNormal;
}

- (BOOL)hasTopSegment
{
    return YES;
}

+ (NYViewControllerNavigationBarType)navigationBarType {
    
    return NYViewControllerNavigationBarTypeBlue;
}

- (ZFPlayerControlView *)controlView {
    if (!_controlView) {
        _controlView = [ZFPlayerControlView new];
        UIView * mackIcon = [[UIView alloc]init];
        mackIcon.backgroundColor = [UIColor NYMaskPlayerColor];
        [_controlView addSubview:mackIcon];
        [_controlView sendSubviewToBack:mackIcon];
        UIView * mackUrlIcon = [[UIView alloc]init];
        mackUrlIcon.backgroundColor = [UIColor NYMaskPlayerColor];
        [_controlView addSubview:mackUrlIcon];
        [_controlView sendSubviewToBack:mackUrlIcon];
        [mackIcon mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_controlView.mas_top);
            make.left.equalTo(_controlView.mas_left);
            make.width.equalTo(_controlView.mas_width).multipliedBy(4.0/32.0);
            make.height.equalTo(_controlView.mas_width).multipliedBy(4.0/32.0);
        }];
        [mackUrlIcon mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(_controlView.mas_bottom);
            make.right.equalTo(_controlView.mas_right);
            
            if (IS_IPHONEX){
               make.width.equalTo(_controlView.mas_width).multipliedBy(12.0/32.0); make.height.equalTo(_controlView.mas_width).multipliedBy(1.4/32.0);
            }else{
               make.width.equalTo(_controlView.mas_width).multipliedBy(9.0/32.0); make.height.equalTo(_controlView.mas_width).multipliedBy(1.3/32.0);
            }
        }];
    }
    return _controlView;
}

- (NSMutableDictionary *)paraDictionary {
    if (!_paraDictionary) {
        _paraDictionary = [NSMutableDictionary dictionary];
    }
    return _paraDictionary;
}

- (void)saveTheLearnRecordModel:(NYCourseModel *)recordModel {
    
    recordModel.currentPlayModel = self.currentPlayModel;
    recordModel.currentPlayIndex = self.currentPlayIndex;
    recordModel.isRecord = true;
    
    NSMutableDictionary *recordDictionary = [NSMutableDictionary dictionaryWithDictionary:[NSKeyedUnarchiver unarchiveObjectWithFile:APP_LEARNING_RECORD_PATH]];
    
    NSMutableDictionary *userDictionary = [NSMutableDictionary dictionaryWithDictionary:recordDictionary[NYUserManager.user_id]];
    
    NSString *keyChannel = @(NYUserManager.channelID).stringValue;
    NSMutableArray *arrayM = [NSMutableArray arrayWithArray:userDictionary[keyChannel]];
    
    @weakify(self);
    __block BOOL isAdd = true;
    [arrayM enumerateObjectsUsingBlock:^(NYCourseModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        @strongify(self);
        if (obj.id == recordModel.id &&
            obj.currentPlayModel.id == self.currentPlayModel.id) {
            isAdd = false;
            *stop = true;
        }
    }];
    if (isAdd) {
        
        [arrayM addObject:recordModel];
        [userDictionary setObject:arrayM forKey:keyChannel];
        [recordDictionary setObject:userDictionary forKey:NYUserManager.user_id];
        // 保存记录
        [NSKeyedArchiver archiveRootObject:recordDictionary toFile:APP_LEARNING_RECORD_PATH];
    }
}
@end
